/**
Company: Sarkar software technologys
WebSite: http://www.sarkar.cn
Author: yeganaaa
Date : 5/18/18
Time: 3:26 PM
 */

package Cn.Sarkar.IMS.Entities.DataSources.Feature

import com.beust.klaxon.JsonObject
import com.beust.klaxon.Klaxon
import io.ktor.client.features.json.JsonSerializer
import io.ktor.client.response.HttpResponse
import io.ktor.content.OutgoingContent
import io.ktor.content.TextContent
import io.ktor.http.ContentType
import kotlinx.coroutines.experimental.io.jvm.javaio.toInputStream
import kotlin.reflect.KClass

class KlaxonJsonSerializer : JsonSerializer {
    val klaxon = Klaxon()
    override suspend fun read(type: KClass<*>, response: HttpResponse): Any {

        return klaxon.fromJsonObject(klaxon.parser(type).parse(response.content.toInputStream()) as JsonObject, type.java, type)

//        return klaxon.parser(type).parse(response.content.toInputStream())
//                ?: throw Exception("Cannot deserialize object from json content...")
    }

    override fun write(data: Any): OutgoingContent {
        return TextContent(klaxon.toJsonString(data), ContentType.Application.Json)
    }
}